package it.polimi.TravelDream.ejb.eaos;

import java.util.ArrayList;
import java.util.List;

import it.polimi.TravelDream.ejb.dtos.ExcursionDTO;
import it.polimi.TravelDream.ejb.entities.BasicPackage;
import it.polimi.TravelDream.ejb.entities.Excursion;

import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

/**
 * Session Bean implementation class ExcusionEAO
 */
@Stateless
public class ExcusionEAO implements ExcursionList {

	@PersistenceContext
	private EntityManager em;
	
    /**
     * Default constructor. 
     */
    public ExcusionEAO() {
    }
    
    @Override
    public void add(ExcursionDTO excursionDTO){
    	Excursion excursion = new Excursion(excursionDTO);
    	
    	em.persist(excursion);
    	this.insertIntoOldPackage(excursion);
    }
    	
    	//Inserisco le nuove escursioni nei pacchetti disponibili se condividono la nazione
    private void insertIntoOldPackage(Excursion excursion) {
    	List<BasicPackage> listOfPackage = new ArrayList<BasicPackage>();
    	
    	listOfPackage = em.createNamedQuery(BasicPackage.FIND_ALL_AVAILABLE_PACKAGE, BasicPackage.class).getResultList();
		for(BasicPackage p: listOfPackage) {
			if( p.getNation().equals(excursion.getNation())) {
				if( !p.getExcursions().contains(excursion) ){
					p.getExcursions().add(excursion);
				}
			}
		}
    }
    
}
